package cn.hl.basic.util;

import cn.hl.basic.jwt.JwtUtils;
import cn.hl.basic.jwt.LoginData;
import cn.hl.basic.jwt.Payload;
import cn.hl.basic.jwt.RsaUtils;
import cn.hl.user.domain.Logininfo;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

/**
 * 获取当前登录人的信息
 */
public class LoginContext {

    public static Logininfo getLogininfo(HttpServletRequest request) {
        try {
            // 1.从请求头中获取token的值
            String token = request.getHeader("token");
            if (token != null) {
                // 2.获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                // 3.对登录数据进行解密
                Payload<LoginData> infoFromToken = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                // 4.返回登录人的信息
                return infoFromToken.getLoginData().getLogininfo();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
